define(["jquery","site_tip","comm","glable_mask","stylishSelect","laydate","plugin/jquery.form","mustache.min","text!/static/page/policies.html","site_tip","plugin/qtip/jquery.qtip.min","css!/static/js/jquery/qtip/jquery.qtip.css","plugin/jquery.cookie"],function($,Site_tip,comm,Glable_mask,stylishSelect,laydate,Jfrom,Mustache,PolicyTpl) {
	var site_tip = new Site_tip();
			//comm.loadCss("/static/js/jquery/qtip/jquery.qtip.css");
	function Policies(){
		//1:时间段 2：具体时间
		this.timeType = 1;
		this.glable_mask = null;
		//0:文件  1：文件夹
		this.type = 0;
		this.batchParam = null;
		this.firstShow=1;
	}



	Policies.prototype.init = function(tData) {
		//console.log("adsfasdfasdf");
		this.loadData(tData);
	}
	
	Policies.prototype.loadData = function(tData) {
		this.loadTpl(tData);
	}

	Policies.prototype.loadDataByAjax = function(params,url,loadData,cb)
	{
		loadData = loadData==undefined?true:loadData;
		var that = this;
		if(!that.glable_mask)
		{
			that.glable_mask = new Glable_mask();
		}
		var getDataAjaxProcess;
		that.glable_mask.add($('<div class="policies" id="set_policies"><div class="panel"><div class="title">访问控制 <button class="close" type="button">×</button> </div> <div class="content"></div></div></div>'),true,function(){
			if(getDataAjaxProcess)
			{
				getDataAjaxProcess.abort();
			}
		});
		$("#set_policies").show();
		that.glable_mask.update();
		that.glable_mask.addLoadingView();
		url = url|| "/policies";
		if(params)
		{
			if(params.type==1)
			{
				that.type=1;
			}
			getDataAjaxProcess=$.ajax({
				method:'get',
				data:params,
				url:url,
				dataType:"json",
				success:function(ret){
					if($("#set_policies").length>0)
					{
						if(loadData && ret.data)
						{
							$("#set_policies").remove();
							that.reloadTpl(ret.data);
						}
						else if(!ret.success)
						{
							site_tip.setContent(ret.message);
							$("#set_policies .close").trigger("click");
						}
						if(cb && $.isFunction(cb))
						{
							cb(ret,that.glable_mask);
						}
						that.glable_mask.removeLoadingView();
					}
				},
				error:function(e)
				{
					comm.ajaxErrorCommon(e);
					that.glable_mask.remove();
				}
			});
		}
	}

	Policies.prototype.reloadTpl = function(tdata)
	{
		var that = this;
		var renderedPage = Mustache.to_html(PolicyTpl, tdata);
		that.glable_mask.remove();
		that.glable_mask.add($(renderedPage),true);
		that.bindUI(tdata);
		that.timeType = $("#set_policies").find("input[name='time_type']").val();
		$("#set_policies").show();
		that.glable_mask.update();
	}
	
	Policies.prototype.loadTpl = function(tdata) {
		var that = this;
		var renderedPage = Mustache.to_html(PolicyTpl, tdata);
		if(tdata == null || tdata == undefined){
			$("#set_policies").find("input[name='time_type']").val(1);
		}
		if(!that.glable_mask)
		{
			that.glable_mask = new Glable_mask();
		}
		that.glable_mask.add($(renderedPage),true);
		that.bindUI.apply(that,[tdata]);
		that.timeType = $("#set_policies").find("input[name='time_type']").val();
		$("#set_policies").show();
		that.glable_mask.update();
		return false;
	}
	
	Policies.prototype.bindUI = function(tdata,bindUICallback) {
		//console.log(tdata);
		var that = this;
		
		var $inputpwd = $('#j_inputpwd');
		//判断密码状态
		if(tdata == undefined || tdata.f_pwd=='' || tdata.f_pwd==null || tdata.f_pwd=='0'){
			$('#j_setpwd').show();
			$inputpwd.find('input.is-read-pwd').val('off');
		} else {
			$('#j_inputpwd').show();
			$inputpwd.find('input.is-read-pwd').val('on');
		}
		
		//设置查阅密码
		$('#j_setpwd').on('click', function(){
			var rStr = randomString(4);
			$(this).hide();
			$inputpwd.find('input.read-pwd').val(rStr);
			$inputpwd.find('.icon-copy').attr('data-clipboard-text', rStr);
			$inputpwd.find('input.is-read-pwd').val('on');
			$inputpwd.show();
		});
		
		//删除查阅密码
		$('#j_deletepwd').on('click', function(){
			$inputpwd.find('input').val('');
			$inputpwd.find('input.is-read-pwd').val('off');
			$inputpwd.hide();
			$('#j_setpwd').show();
			$inputpwd.find('.error').text('');
		});
		
		//输入密码处理
		$inputpwd.find('input.read-pwd').on('keyup', function(){
			var reg = /[^A-Za-z0-9]/g;
			var val = $(this).val();
			if(reg.test(val) && val != '') {
				$(this).val(val.replace(reg, ''));
			}
		});
		$inputpwd.find('input.read-pwd').on('blur', function(){
			var val = $(this).val();
			if(val.length < 4){
				var errorText = '密码不足四位';
				$inputpwd.find('.error').text(errorText);
			} else {
				$inputpwd.find('.error').text('');
			}
		});
		
		$("#set_policies").find(".close").click(function(e) {
			comm.stopEvent(e);
			that.glable_mask.remove();
			that.glable_mask = null;
			
			$(".xdsoft_datetimepicker.xdsoft_noselect").remove();
		});
		
		$('select').sSelect({minContainer:$("#set_policies")});
		//动态检查时间并刷新时间
		var timePickerTimer;
		function checkTimePickerHandler(){
			var picker = $('#datetimepicker');
			if(picker.length<=0)
			{
				stopTimePickerCheck();
				return;
			}
			var val = picker.val();
			var curTime = new Date().getTime();
			//console.log(Date.parse(val.replace(/\-/,"/")) < curTime);
			if(val!="" && Date.parse(val.replace(/\-/,"/")) < curTime)
			{
				if($("#laydate_box").length<=0 || $("#laydate_box").is(":hidden"))
				{
					var fixTime = curTime+3600*24*1000;
					picker.val(laydate.now(fixTime,"YYYY-MM-DD hh:mm:ss"));
				}
			}
		}
		//检查时间
		function checkDateTime(showError){
			var timeBox = $('#datetimepicker');
			var val = timeBox.val();
			var curTime = new Date().getTime();
			var inputTime = Date.parse(val.replace(/\-/g,"/"));
			//console.log(val);
			//console.log(Date.parse(val.replace(/\-/,"/")) < curTime);
			if(val =="" || !inputTime)
			{
				//时间格式错误
				if(showError)
				{
					showDateTimeError("格式错误");
				}
				return 1;
			}
			else if(inputTime < curTime)
			{
				//时间范围错误
				if(showError)
				{
					showDateTimeError("输入时间不能小于当前时间");
				}
				return 2;
			}
			else
			{
				//验证通过
				if(showError)
				{
					hideDateTimeError();
				}
				return 0;
			}
		}
		function startTimePickerCheck(){
			//console.log("start");
			checkTimePickerHandler();
			timePickerTimer = setInterval(checkTimePickerHandler,1000);
		}
		function stopTimePickerCheck(){
			//console.log("stop");
            clearInterval(timePickerTimer);
		}

		var view = new Object();
		//初始化
		view.is_expired_time_custom = "off";
		view.is_expired_time = "off";
		view.is_expired_time2 = "off";
		view.is_only_one = "off";
		view.is_auto_del = "off";
		/*checkExpTime(false);
		checkExpTime2(false);
		checkOnlyOne(false);
		checkAutoDel(false);*/
		if(that.batchParam != null && that.batchParam.isBatch){
			view.file_uuids = that.batchParam.fileUuids;
			view.folder_uuids = that.batchParam.folderUuids;
		}

		//检测是否为数字
		function checkKeyCode(k) {
			if (k >= 48 && k <= 57) {
				return true;
			}

			if (k >= 96 && k <= 105) {
				return true;
			}

			return false;
		}

		//默认选中只可查阅一次
		var openTimeObj = $('#opened_times');
		var openTimeShow = $('#opened_times_show');
		openTimeShow.click(function() {
			$(this).hide();
			//当清空值后，点击框时
			if (openTimeObj.val() == '') {
				openTimeObj.val(1);
			}
			openTimeObj.show();
			// openTimeObj.trigger("focus");
			 var myVal = openTimeObj.val();
			 openTimeObj.val("").trigger("focus").val(myVal);
		});
		openTimeObj.blur(function() {
			openTimeShow.show();
			$(this).hide();
		});

		openTimeObj.bind({
			keydown: function(e) {

				//shift按下均不可操作
				if (e.shiftKey) {
					return false;
				}

				if ((e.keyCode == 8) ||
					(e.keyCode >= 48 && e.keyCode <= 57) ||
					(e.keyCode >= 96 && e.keyCode <= 105)) {
					return true;
				}

				return false;
			},
			keyup: function() {
				var maxVal = 9999999;
				var minVal = 1;
				var inval = $(this).val();
				var val = 1;

				//fix 输入法状态下输入帐号时
				if (inval != "") {
					var toNum = parseInt(inval);
					if (! isNaN(toNum)) {
						val = toNum;
					}
				}

				if (val < minVal)
					val = 1;

				if (val > maxVal)
					val = maxVal;

				//清空值时
				if (inval != "") {
					$(this).val(val);
				}

				openTimeShow.val(val + "次");
			}
		});

		if(tdata == undefined || tdata.is_new)
		{
			openTimeObj.val(1);
			openTimeShow.val(1 + "次");
			checkOnlyOne(true);
		}
		else if(tdata.open_counter === 0) {
			//view.is_only_one = "off";
			openTimeObj.val(1);
			openTimeShow.val(1 + "次");
			checkOnlyOne(false);
		} else {
			/*$("#is_only_one").toggleClass("icon-checkbox-hover");
			 view.is_only_one = "on";
			 $("#set_policies").find(".auto_del").show();*/
			openTimeObj.val(tdata.open_counter);
			openTimeShow.val(tdata.open_counter + "次");
			checkOnlyOne(true);
		}

		function open_unlimit(flag) {
			if (flag) {
				$('#opened_unlimit_show').show();
				return;
			}

			$('#opened_unlimit_show').hide();
		}

		/*var timePlugin = $("#set_policies").find(".glyphicon-time");
		timePlugin.click(function(e) {
			comm.stopEvent(e);
			if(that.timeType == 1){
				that.timeType = 2;
			}else{
				that.timeType = 1;
			}
			that.selectTime(that.timeType,view);
		});*/
		
		/*var now = new Date();
		var curyear = now.getFullYear(); // 年*/
		
		/*var logic = function( currentDateTime,$input ){
			  // 'this' is jquery object datetimepicker
			  var now = new Date();
			  if( currentDateTime.getDate() == now.getDate() ){
				  this.setOptions({
					  timepicker:true,
					  minTime: now.getHours()+":"+now.getMinutes()
				  });
				  return;
			  }
			  
			  this.setOptions({
				  timepicker:true,
			      minTime:'00:00'
			  });
		};*/
		
		
		
		/*var changeYear = function(current_time,$input){
			var now = new Date();
			if( current_time.getFullYear() < curyear ){
				 this.setOptions({
					 timepicker:false
				  }); 
			}else{
				this.setOptions({
					 timepicker:true
				});
			}
		};*/
		
		/*var changeMonth = function(current_time,$input){
			var now = new Date();
			if( current_time.getFullYear() < curyear ){
				 this.setOptions({
					 timepicker:false
				  }); 
			}else{
				if(current_time.getFullYear() == curyear){
					if( current_time.getTime() >= now.getTime() ){
						this.setOptions({
							 timepicker:true,
							 minTime: '00:00'
						});
						if(current_time.getTime() == now.getTime()){
							this.setOptions({
								minTime: now.getHours()+":"+now.getMinutes()
							});
						}
						return;
					}
					
					this.setOptions({
						 timepicker:false
					});
					return;
				}
				return;
				this.setOptions({
					 timepicker:true
				});
			}
			
			
		};*/
		
		if (tdata != undefined && tdata.life_span != 0 && tdata.life_span != null) {
			/*$("#is_expired_time").addClass("icon-checkbox-hover");
			view.is_expired_time = "on";*/
			checkExpEnable(true);
			checkExpTime(true);

			/*$("#set_policies").find(".auto_del").show();
			$('#datetimepicker').show();
			$('#datetimepicker').trigger('open.xdsoft');*/
			//$('#time_txt').html("前");
			//$("#set_policies").find(".newListSelected").hide();
			//var life_span = tdata.life_span;
			//var time = life_span.substring(life_span.length - 5);
			/*$('#datetimepicker').datetimepicker({
				format:'Y-m-d H:i',
				lang : 'ch',
				minDate:tdata.life_span,
				onChangeDateTime:logic,
				onShow:logic,
				onChangeYear:changeYear,
				onChangeMonth:changeMonth,
				yearStart:curyear
			});*/
			//console.log(tdata.life_span);
			$('#datetimepicker').val(tdata.life_span);
			//timePlugin.hide();
		} else {
			//timePlugin.show();
			/*$("#is_expired_time").removeClass("icon-checkbox-hover");
			view.is_expired_time = "off";*/
			checkExpEnable(false);
			checkExpTime(false);
			/*if(!$("#is_only_one").hasClass("icon-checkbox-hover")){
				$("#set_policies").find(".auto_del").hide();
				$("#is_auto_del").removeClass("icon-checkbox-hover");
				view.is_auto_del = "off";
			}*/
			//var curtime = CurentTime();
			//var time = curtime.substring(curtime.length - 5);
			/*$('#datetimepicker').datetimepicker({
				format:'Y-m-d H:i',
				lang : 'ch',
				minDate:curtime,
				onChangeDateTime:logic,
				onShow:logic,
				onChangeYear:changeYear,
				onChangeMonth:changeMonth,
				yearStart:curyear
			});*/
			//console.log("ssss");
			$('#datetimepicker').val(laydate.now((new Date().getTime()+3600*24*1000),"YYYY-MM-DD hh:mm:ss"));

		}
		//开启动态检查时间合法性并更新
		//startTimePickerCheck();

		if (tdata == undefined || tdata.delete_after_expired != "1") {
			//view.is_auto_del = "off";
			checkAutoDel(false);
		} else {
			/*$("#is_auto_del").toggleClass("icon-checkbox-hover");
			 view.is_auto_del = "on";
			 $("#set_policies").find(".auto_del").show();*/
			checkAutoDel(true);
		}
		var dateTimeErrMsgBox = $("#date-error-msg-box");
		function showDateTimeError(msg){
			dateTimeErrMsgBox.text(msg).show();
		}
		function hideDateTimeError(){
			dateTimeErrMsgBox.text("").hide();
		}

		/**
		 * 生成时间控件
		 */
		function generateDateTimePicker(){
			/*if(checkDateTime()!=0)
			{
				return;
			}*/
			//console.log("sfasdfas");


			laydate({
				elem: '#datetimepicker',
				min: laydate.now(new Date().getTime(),"YYYY-MM-DD hh:mm:ss"),
				format:"YYYY-MM-DD hh:mm:ss",
				istime:true,
				isclear:false,
				istoday:false,
				issure:false,
				//start:laydate.now(new Date().getTime(),"YYYY-MM-DD hh:mm:ss"),
				choose:function(val){
					checkExpTime(true);
					//autoDelView();
				},
				afterClose:function(){
					$("#datetimepicker-icon").removeClass("expand");
				},
				afterError:function(errType,errMsg){
					//console.log(errMsg);
				}
			});
		}
		//generateDateTimePicker();

		/**
		 *   自动校正时间格式并检查时间合法性
		 */
		function autoCorrectTimeAndCheck(autoFixHms){
			var timeBox = $("#datetimepicker");
			var val = timeBox.val();
			val = $.trim(val);
			//console.log(val.match(/^(\d){4}(\d)$/g));
			//第一种情况 YYYY-MM-DD hh:mm:ss
			var time;
			/*var test1 = val.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s(\d{1,2}):(\d{1,2}):(\d{1,2})$/);
			//([0-9]|[0-1][0-9]|2[0-4])([0-9]|[0-5][0-9]|60)
			var test2 = val.match(/^(\d{4})(-{0,1}|\/{0,1}|\\{0,1})([0-9]|0[0-9]|1[0-2])(-{0,1}|\/{0,1}|\\{0,1})([0-9]|[0-2][0-9]|30|31)((\s{0,1})([0-9]|[0-1][0-9]|2[0-4])(:{0,1})([0-9]|[0-5][0-9]|60)(:{0,1})([0-9]|[0-5][0-9]|60)){0,1}$/);*/

			/*
			 * 匹配的索引值 1:年 3:月 5:日 9:时 11:分 13:秒
			 * @author:洪彬富<hongbinfu@163.com>
			 * @readme:可以匹配不输入时分秒的情况
			 */
			var test = val.match(/^(\d{4})([^\d]{0,1})(1[0-2]|0[1-9]|[1-9])([^\d]{0,1})(31|30|[1-2][0-9]|0[1-9]|[1-9])(([^\d]{0,1})(2[0-4]|[0-1][0-9]|[0-9])([^\d]{0,1})(60|[0-5][0-9]|[0-9])([^\d]{0,1})(60|[0-5][0-9]|[0-9])){0,1}$/);

			//&& timeBox[0].checkMonth(test[1],test[3])
			var test2 = val.match(/^(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})$/);
			var checkMonth = false;
			if(test)
			{
				checkMonth = timeBox[0].checkMonth(test[1],test[3],test[5]);
			}
			//console.log(checkMonth);
			//console.log(test[1]+"==="+test[3]+"=="+test[5]);
			if(test && checkMonth)
			{
				//console.log(test);
				/*var curTime = new Date();
				var minY = curTime.getFullYear();
				var minM = curTime.getMonth();
				var minD = curTime.getDate();
				var minH = curTime.getHours();
				var minI = curTime.getMinutes();
				var minS = curTime.getSeconds();*/
				/*var curTime;
				if(curTime>minY)
				{
					console.log("你输入的年份不能小于"+minY);
				}
*/

				//var curTime = new Date();
				//var mins = [curTime.getFullYear(),curTime.getMonth(),curTime.getDate()];
				//var mins2 = [curTime.getHours(),curTime.getMinutes(),curTime.getSeconds()];
				//[De.getFullYear(), De.getMonth(), De.getDate(),De.getHours(),De.getMinutes(),De.getSeconds()];
				var ymd = [test[1],test[3],test[5]];
				ymd[3]=test[8]||0;
				ymd[4]=test[10]||0;
				ymd[5]=test[12]||0;
				//console.log(ymd[0]+"/"+ymd[1]+"/"+ymd[2]+" "+ymd[3]+":"+ymd[4]+":"+ymd[5]);
				//console.log(Date.parse(ymd[0]+"/"+ymd[1]+"/"+ymd[2]+" "+ymd[3]+":"+ymd[4]+":"+ymd[5])+"=="+curTime);
				/*if(Date.parse(ymd[0]+"/"+ymd[1]+"/"+ymd[2]+" "+ymd[3]+":"+ymd[4]+":"+ymd[5])<curTime.getTime())
				{

					showDateTimeError("输入时间不能小于当前时间");
					//return;
				}*/
				var v = timeBox[0].digit(ymd[0])+"-"+timeBox[0].digit(ymd[1])+"-"+timeBox[0].digit(ymd[2]);
				/*if(test[8]!="undefined" && autoFixHms)
				{

				}*/
				v +=" "+timeBox[0].digit(ymd[3])+":"+timeBox[0].digit(ymd[4])+":"+timeBox[0].digit(ymd[5]);
				//console.log(test2);
				if(!test2)
				{
					timeBox.val(v);
				}
				var laydateBox = $("#laydate_box");
				if(laydateBox.length>0 && laydateBox.is(":visible"))
				{
					timeBox[0].reshow(ymd);
				}
				var chkDatetime = checkDateTime(true);
				//console.log(chkDatetime);
				/*if(chkDatetime)
				{
					hideDateTimeError();
				}*/
			}
			else if(!test2 || !checkMonth)
			{
				showDateTimeError("格式错误");
			}
			else if(checkDateTime()!=0)
			{
				showDateTimeError("输入时间不能小于当前时间");
			}
			else{
				hideDateTimeError();
			}
		}
		$('#datetimepicker').bind({
			"click":function(e){
				//console.log("ssss");
				$("#datetimepicker-icon").addClass("expand");
			    var laydateBox = $("#laydate_box");
				if(laydateBox.length<=0 || laydateBox.is(":hidden"))
				{
					generateDateTimePicker();
				}
				else{
					autoCorrectTimeAndCheck();
				}
			},
			"blur":function(){
				autoCorrectTimeAndCheck(true);
			}/*,
			"selectstart":function(){
				console.log("sssss");
				var laydateBox = $("#laydate_box");
				if(laydateBox.length<=0 || laydateBox.is(":hidden"))
				{
					generateDateTimePicker();
				}
			}*/
		});
		$("#datetimepicker-icon").click(function(){
			//console.log("ssssssss");
			$('#datetimepicker').trigger("click");
		});
		$("#is_expired_time").click(function(e) {
			comm.stopEvent(e);
			//$(this).toggleClass("icon-checkbox-hover");
			//var flag = $(this).hasClass("icon-radio-hover");
			checkExpTime(true);
		});
		var expTimeMode = 1;
		function checkExpTime(flag)
		{
			if (flag == true) {
				$("#is_expired_time").addClass("icon-radio-hover");
				view.is_expired_time = "on";
				//$("#set_policies").find(".auto_del").show();

				//时间段和时间只能选其一
				if(expTimeMode==1)
				{
					$("#is_expired_time2").removeClass("icon-radio-hover");
					view.is_expired_time2 = "off";
				}
				//动态检查时间
				//startTimePickerCheck();
			} else {
				$("#is_expired_time").removeClass("icon-radio-hover");
				view.is_expired_time = "off";
				//关闭动态检查时间
				//console.log("heihei,stop");
				//stopTimePickerCheck();
			}
			autoDelView();

		}
		function checkExpEnable(flag){
			var chkBox =$("#enable-exp-time-setting");
			var exp1 = $("#is_expired_time");
			var exp2 = $("#is_expired_time2");
			if (flag == true) {
				chkBox.addClass("icon-checkbox-hover");
				if(!exp1.hasClass("icon-radio-hover") && !exp2.hasClass("icon-radio-hover"))
				{
					checkExpTime(true);
				}
				//$(".time-group").slideDown();
			} else {
				//$(".time-group").slideUp();
				chkBox.removeClass("icon-checkbox-hover");
				checkExpTime(false);
				checkExpTime2(false);
			}
			autoDelView();
		}
		$("#enable-exp-time-setting").click(function(e) {
			comm.stopEvent(e);

			//$(this).toggleClass("icon-checkbox-hover");
			var flag = $(this).hasClass("icon-checkbox-hover");
			checkExpEnable(!flag);
		});
		/**
		 * 选择时段 或者自定义时间checkbox
		 */
		$("#is_expired_time2").click(function(e) {
			comm.stopEvent(e);

			//$(this).toggleClass("icon-checkbox-hover");
			//var flag = $(this).hasClass("icon-checkbox-hover");
			checkExpTime2(true);
		});
		/**
		 * 选择自定义时间段
		 * @param flag true:显示 false:隐藏
		 */
		function checkExpTime2(flag)
		{
			if (flag == true) {
				$("#is_expired_time2").addClass("icon-radio-hover");
				view.is_expired_time2 = "on";
				//$("#set_policies").find(".auto_del").show();
				//时间段和时间只能选其一
				if(expTimeMode==1) {
					$("#is_expired_time").removeClass("icon-radio-hover");
					view.is_expired_time = "off";
				}
			} else {
				$("#is_expired_time2").removeClass("icon-radio-hover");
				view.is_expired_time2 = "off";
			}
			autoDelView();
		}

		//只能阅读一次checkbox
		$("#is_only_one").click(function(e) {
			comm.stopEvent(e);
			//$(this).toggleClass("icon-checkbox-hover");
			var flag = $(this).hasClass("icon-checkbox-hover");
			checkOnlyOne(!flag);
		});
		function checkOnlyOne(flag)
		{
			if (flag == true) {
				open_unlimit(false);
				$("#is_only_one").addClass("icon-checkbox-hover");
				view.is_only_one = "on";
				//$("#set_policies").find(".auto_del").show();
				//$("#opened_times").show();
				$("#opened_times_show").show();
			} else {
				$("#is_only_one").removeClass("icon-checkbox-hover");
				view.is_only_one = "off";
				$("#opened_times").hide();
				$("#opened_times_show").hide();
				open_unlimit(true);

			}
			autoDelView();
		}
		function resetPanelPos(){
			//console.log("sss");
			that.glable_mask.update(true);
		}
		/*
		 * 自动销毁行显示逻辑
		 * 只要时间、阅读时长、阅读一次，只要勾选其一则显示
		 */
		function autoDelView(animate,cb){
			animate = (animate==undefined)?true:animate;
			var panel = $(".policies .panel");
			//panel.css("height","auto");
			//var height = 331;
			var expEnable = $("#enable-exp-time-setting").hasClass("icon-checkbox-hover");
			var expChk = $("#is_expired_time").hasClass("icon-radio-hover");
			var exp2Chk = $("#is_expired_time2").hasClass("icon-radio-hover");
			var onlyOneChk = $("#is_only_one").hasClass("icon-checkbox-hover");
			var autoDel = $("#set_policies").find(".auto_del");
			if(expEnable || onlyOneChk){
				animate?autoDel.slideDown("fast"):autoDel.show();
				//$("#is_auto_del").addClass("icon-checkbox-hover");
				//view.is_auto_del = "on";
				//$(".policies .panel").css("height",410);
			}
			else
			{
				animate?autoDel.slideUp("fast"):autoDel.hide();
				$("#is_auto_del").removeClass("icon-checkbox-hover");
				view.is_auto_del = "off";
				//$(".policies .panel").css("height",370);
			}
			/*if(expEnable)
			{
				height = 443;
			}
			else if(!expEnable && onlyOneChk)
			{
				height = 373;
			}
			panel.animate({height:height});*/
			if(animate)
			{
				expEnable?$(".time-group").slideDown("fast",resetPanelPos):$(".time-group").slideUp("fast",resetPanelPos);
			}
			else{
				expEnable?$(".time-group").show():$(".time-group").hide();
			}
			//console.log($("#set_policies").height());
		}
		//自动销毁checkbox
		$("#is_auto_del").click(function(e) {
			comm.stopEvent(e);
			//$(this).toggleClass("icon-checkbox-hover");
			var flag = $(this).hasClass("icon-checkbox-hover");
			checkAutoDel(!flag);
		});
		function checkAutoDel(flag){
			//console.log(flag);
			if (flag == true) {
				$("#is_auto_del").addClass("icon-checkbox-hover");
				view.is_auto_del = "on";
			} else {
				$("#is_auto_del").removeClass("icon-checkbox-hover");
				view.is_auto_del = "off";
			}
		}
		//提交表单
		$("#secury_btn").click(function(e) {
			if($('.is-read-pwd').val() == 'on'){
				var val = $('#j_inputpwd').find('.read-pwd').val();
				if(val.length < 4){
					return false;
				}
			}
			comm.stopEvent(e);
			
			//根据this.isBatch选择url
			var url = "/policies/update?type="+that.type;
			if(that.batchParam != null && that.batchParam.isBatch){
				url = "/policies/updateBatch";
			}
			//console.log("hhhhhh");
			update_secury(view,url);
		});

		//处理自定义时间段
		/*function checkTimeSlot(newVal,oldVal,min,max)
		{

		}*/
		$(".time_slot_input").bind({
			focus:function(){
				checkExpTime2(true);
			},
			keydown:function(){
				var me = $(this);
				me.data("oldVal",me.val());
			},
			keyup:function(){
				var me = $(this);
				var newVal = me.val()===0?0:parseInt(me.val());
				var oldVal = parseInt(me.data("oldVal")) || "";
				var min = parseInt(me.attr("min")) || 0;
				var max = parseInt(me.attr("max"));
				var insert;
				//console.log(newVal);
				if(newVal===0)
				{
					insert = 0;
				}
				else if(newVal == "NaN")
				{
					insert = oldVal;
				}
				else if(max>0 && newVal>max)
				{
					insert = max;
				}
				else if(newVal<min)
				{
					insert = min;
				}
				else{
					insert = newVal||"";
				}
				me.val(insert);
			},
			blur:function(){
				var find = false;
				if($(this).val()=="")
				{
					$(this).val(0);
				}
				$(".time_slot_input").each(function(){
					var val = parseInt($(this).val())||0;
					if(val>0)
					{
						find=true;
						return false;
					}
				});
				//console.log(find);
				checkExpTime2(find);


			}
		});
		$("#show_time_slot_select").click(function(){
			toggleShowCustomTimeSlot(false);
			$("#time_slot").val(3).trigger("change");
		});
		//显示自定义时间段
		function toggleShowCustomTimeSlot(flag)
		{
			var box = $("#time_custom");
			var select = $("#time_select");
			if(flag==true)
			{
				box.show();
				select.hide();
				view.is_expired_time_custom = "on";
			}
			else{
				//清空已经输入的内容
				$(".time_slot_input").each(function(){
					var v = $(this).is("[name='time_slot_s']")?10:0;
					$(this).val(v);
				});
				box.hide();
				select.show();
				view.is_expired_time_custom = "off";
			}
		}

		//下拉时间段事件
		var select = $("#set_policies").find(".newListSelected");
		select.bind("click", function() {
			var val = $("#time_slot").val();
			/*$("#is_expired_time2").addClass("icon-checkbox-hover");
			view.is_expired_time2 = "on";
			$("#set_policies").find(".auto_del").show();
			$("#is_expired_time").removeClass("icon-checkbox-hover");
			view.is_expired_time = "off";*/
			checkExpTime2(true);
			if(val=="0")
			{
				toggleShowCustomTimeSlot(true);
			}
		});
		//时间选择框
		var datetimepicker = $("#datetimepicker");
		datetimepicker.bind("click", function() {
			/*$("#is_expired_time").addClass("icon-checkbox-hover");
			view.is_expired_time = "on";
			$("#is_expired_time2").removeClass("icon-checkbox-hover");
			view.is_expired_time2 = "off";*/
			checkExpTime(true);
		});
		//回车提交
		$(document).bind("keydown", function (e) {
			comm.stopEvent(e);
			var oEvent = window.event ? e.keyCode : e.which;
			if (oEvent == 13) {
				// alert("你按下了Tab键");
				
				//根据this.isBatch选择url
				var url = "/policies/update?type="+that.type;
				if(that.batchParam != null && that.batchParam.isBatch){
					url = "/policies/updateBatch";
				}
				
				update_secury(view,url);
			}
		});
		
		
		//提交设置实现函数
		function update_secury(view,url) {
			if(view.is_expired_time=="on" && checkDateTime(true)!=0)
			{
				return false;
			}
			var form = $("#secury_form");
			form.attr("action",url);
			var data = form.serialize()+"&"+$.param(view);
			//view.f_id = form.find("[name=f_id]").val();
			//view.time_type = form.find("[name=time_type]").val();
			var options = {
				url:url,
				type : "POST",
				data : data,
				dataType : 'json',
				success : function(jsonData) {
					$("#secury_btn").attr("disabled",false).text("保存");
					// alert("设置保护成功");
					if (jsonData.ret == -1) {
						/*if(glable_mask != null){
							glable_mask.remove();
						}*/
						/*if(that.batchParam != null && that.batchParam.isBatch){
							return;
						}*/
						
						if($("#wfo").data("detail") == 1){
							require(["folder/main"],function(Folder){
								var folder = new Folder();
								folder.showDetail();
							});
						}
						//console.log($("#set_policies").find(".close"));
						$("#set_policies").find(".close").trigger("click");
						site_tip.setContent("设置成功");
					} else {
						site_tip.setContent("设置失败");
					}

				}
			};
			$("body").one("networkError",function(){
				$("#secury_btn").attr("disabled",false).text("保存");
			});
			/*var data = form.serializeArray();
			$.each(view,function(k,v){
				data.push({name:k,value:v});
			});
			//console.log(data);return;
			//data = $.extend({},data,view);
			$("#secury_btn").attr("disabled",true);
			$.post(url,data,function(jsonData){
				$("#secury_btn").attr("disabled",false);
				var tip = new Site_tip();
				if (jsonData.ret == -1) {
					if(glable_mask != null){
						glable_mask.remove();
					}
					if(that.batchParam != null && that.batchParam.isBatch){
						return;
					}

					if($("#wfo").data("detail") == 1){
						require(["folder/main"],function(Folder){
							var folder = new Folder();
							folder.showDetail();
						});
					}
				} else {
					tip.isAnimal=true;
					tip.setContent("设置失败");
				}
			},"json");*/
			$("#secury_btn").attr("disabled",true).text("保存中...");
			$.ajax(options);
		}
		
		var clipUrl = "clipboard";
		if(comm.lessThenIE(9) && comm.isIE()){
			clipUrl = "clipboardLess";
		}
		if($.cookie("noFlash")=="yes")
		{
			$("#set_policies").find(".icon-copy").qtip({
				content: '不能自动复制，请使用“Ctrl+C”或者右键“复制”查阅密码到剪贴板',
				position:{
					at: 'top center',
					my:'bottom center'
				},
				show: {
					event:'click',
					effect: false
				},
				hide: {
					event:'unfocus',
					effect: false
				}
			});
		}
		else{
			require([clipUrl],function(ZeroClipboard){
				var tg = $("#set_policies").find(".icon-copy");
				var client = new ZeroClipboard(tg);
				client.on('ready', function(readyEvent ) {
					var result = $("#set_policies").find(".copy_result");
					client.on('aftercopy', function(event, args) {
						/*result.html("复制密码成功");
						result.stop();
						result.show();
						result.delay(500).fadeOut();*/
						tg.qtip({
							style:{
								classes:"qtip-blue"
							},
							content: '复制成功',
							position:{
								at: 'top center',
								my:'bottom center'
							},
							show: {
								event: false,
								ready: true,
								effect: false
							},
							hide: {
								event:'unfocus',
								effect: false
							}
						});

					});
					client.on('error', function(event, args) {
						ZeroClipboard.destroy();
						result.html("复制密码失败");
						result.show();
					});
				});
			});
		}

		//autoDelView(false);
	}
	
	Policies.prototype.selectTime = function(type,view) {
		/*var timeType = $("#set_policies").find("input[name='time_type']");
		timeType.val(type);
		$("#set_policies").find(".auto_del").show();
		if (type == 1) {
			$("#set_policies").find(".newListSelected").show();
			$('#datetimepicker').hide();
			$('#time_txt').html("内");
			return;
		}
		
		$("#set_policies").find(".newListSelected").hide();
		$('#datetimepicker').show();
		$('#datetimepicker').trigger('open.xdsoft');
		$("#is_expired_time").addClass("icon-checkbox-hover");
		
		$('#time_txt').html("前");
		view.is_expired_time = "on";
		
		return;*/
	}
	
	/**
	 * 获取当前时间
	 * 
	 * @returns {String}
	 */
	function CurentTime() {
		var now = new Date();

		var year = now.getFullYear(); // 年
		var month = now.getMonth() + 1; // 月
		var day = now.getDate(); // 日

		var hh = now.getHours(); // 时
		var mm = now.getMinutes(); // 分
		var clock = year + "-";

		if (month < 10)
			clock += "0";

		clock += month + "-";

		if (day < 10)
			clock += "0";

		clock += day + " ";
		if (mm > 0) {
			hh = parseInt(hh) + 1;
		}
		if (hh < 10)
			clock += "0";
		clock += hh + ":00";
		return (clock);
	}
	
	/**
	 * 生成随机字符串
	 * 
	 * @returns {String}
	 */
	function randomString(len) {
		len = len || 32;
		var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';/****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		var maxPos = $chars.length;
		var pwd = '';
		for (i = 0; i < len; i++) {
	      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	}
	
	return Policies;
	
});